﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web;
using System.Web.SessionState;
using System.Web.Security;
using Models;
using ConcreteService;
using System.IO;
using Infrastructures;

namespace SponsorshipWeb.Controllers
{
    //[CommonAuthorize]
    public class UserController : ApiController
    {
        UserInfoService service = ServiceFactory.CreateInstance<UserInfoService>();
        UtilService utilservice = ServiceFactory.CreateInstance<UtilService>();
        UserInfoService agentservice = ServiceFactory.CreateInstance<UserInfoService>();
        AssociationService assoService = ServiceFactory.CreateInstance<AssociationService>();
        CompanyService companyService = ServiceFactory.CreateInstance<CompanyService>();

        #region 关于头像

        /// <summary>
        /// 修改头像
        /// </summary>
        /// <returns></returns>
        [CommonAuthorize]
        [HttpPost]
        public IHttpActionResult UpdateLogo()
        {
            var user = AuthUtil.GetAuthentication();
            string userid = user.UserID.ToString();
            var httpPostedFile = HttpContext.Current.Request.Files;
            HttpPostedFile logo = httpPostedFile[0];
            UserInfo userInfo = service.Get<UserInfo>(userid);
            string path = null;
            switch (user.UserType)
            {
                case APPRole.Student:
                    var assorelation = utilservice.ListRelationship(RelationshipFun.AssociationToStudent, userid.ToInt()).FirstOrDefault();
                    var assoc = assoService.Get<Association>(assorelation.NOFrom.ToString());
                    path = FileUtil.SaveFile(logo, FileType.AssoLogo, user.UserID, user.UserID.ToString(), APPRole.Association);
                    assoc.LogoPath = path;
                    assoService.Update(assoc, userid);
                    break;
                case APPRole.Company:

                    var comp = companyService.Get<Company>(userid);
                    path = FileUtil.SaveFile(logo, FileType.CompanyLogo, user.UserID, user.UserID.ToString(), APPRole.Company);
                    comp.LogoPath = path;
                    companyService.Update(comp, userid);

                    break;
                case APPRole.Agent:

                    var agent = agentservice.Get<Agent>(userid);
                    path = FileUtil.SaveFile(logo, FileType.AgentLogo, user.UserID, user.UserID.ToString(), APPRole.Agent);
                    agent.LogoPath = path;
                    companyService.Update(agent, userid);
                    break;
            }
            userInfo.HeadImage = path;
            service.Update(userInfo, userid);
            AuthUtil.Authorize(userInfo);
            return Ok(new ObjectResponse()
            {
                Status = ResponseStatus.OK(),
                ResponseObj = AuthUtil.Authorize(userInfo)
            });
        }

        /// <summary>
        /// 获取头像
        /// </summary>
        /// <returns></returns>
        [CommonAuthorize]
        [HttpGet]
        public IHttpActionResult Get()
        {
            var user = AuthUtil.GetAuthentication();
            if (user == null)
                return Unauthorized();

            Dictionary<string, string> dic = new Dictionary<string, string>();

            switch (user.UserType)
            {
                case APPRole.Student:
                    var assoc = assoService.GetRelationship(user.UserID, RelationshipFun.AssociationToStudent);
                    if (assoc == null)
                        return BadRequest();

                    dic.Add("Name", assoc.Name);
                    dic.Add("Grade", assoc.Grade);
                    dic.Add("LogoPath", SystemConfig.Get("UploadHttpPath") + assoc.LogoPath);

                    break;
                case APPRole.Company:

                    var company = companyService.GetCompany(user.UserID.ToString());
                    if (company == null)
                        return BadRequest();

                    dic.Add("Name", company.Name);
                    dic.Add("Grade", company.Grade);
                    dic.Add("LogoPath", SystemConfig.Get("UploadHttpPath") + company.LogoPath);

                    break;
                case APPRole.Agent:

                    AgentService agentService = ServiceFactory.CreateInstance<AgentService>();
                    var agent = agentService.Get<Agent>(user.UserID.ToString());
                    if (agent == null)
                        return BadRequest();

                    dic.Add("Name", agent.Name);
                    dic.Add("Grade", agent.Grade);
                    dic.Add("LogoPath", SystemConfig.Get("UploadHttpPath") + agent.LogoPath);
                    break;
            }

            return Ok(new DictResponse()
            {
                Status = ResponseStatus.OK(),
                ResponseDict = dic
            });
        }

        #endregion

        #region 修改密码
        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        [CommonAuthorize]
        public IHttpActionResult UpdatePassword([FromBody]UserInfo value)
        {
            var userc = AuthUtil.GetAuthentication();
            if (userc == null)
                return BadRequest("请登录");
            string userID = userc.UserID.ToString();

            string response = string.Empty;
            var user = service.Get<UserInfo>(userID);
            string oldp = value.UserName;
            string newp = value.Password;

            if (oldp != user.Password)
            {
                response = "";
            }
            else
            {
                user.Password = newp;
                service.Update<UserInfo>(user, userID);
                response = "OK";
            }
            return Ok(new StringResponse()
            {
                Status = ResponseStatus.OK(),
                ResponseStr = response
            });
        }
        #endregion

        #region 登录
        [AllowAnonymous]
        public IHttpActionResult Post([FromBody]UserInfo value)
        {
            if (HttpContext.Current.Session == null || HttpContext.Current.Session["ValidateCode"] == null)
            {
                return BadRequest("验证码已过期，请刷新后重试");
            }

            var valcode = HttpContext.Current.Session["ValidateCode"].ToString();

            if (valcode != value.WeChart)
            {
                return BadRequest("验证码错误");
            }
            if (!service.IsUserExist(value.UserName))
            {
                return BadRequest("该手机未注册");
            }
            UserInfo user = service.Login(value.UserName, value.Password);
            if (user == null)
                return BadRequest("用户或者密码错误");
            int companyID = 0;
            int studentID = 0;

            switch (value.UserType)
            {
                case "Company":
                    if (user.Role != APPRole.Company)
                    {
                        return BadRequest("只能用企业账号登录");
                    }
                    var company = companyService.Get<Company>(user.UserNo.ToString());
                    if (company != null)
                        companyID = company.CompanyNO;
                    break;
                case "Agent":
                    if (user.Role != APPRole.Agent)
                    {
                        return BadRequest("只能用代理官账号登录");
                    }
                    break;
                case "Personal":
                    if (user.Role != APPRole.Student)
                    {
                        return BadRequest("只能用社团账号登录");
                    }
                    StudentService stuService = ServiceFactory.CreateInstance<StudentService>();
                    var stu = stuService.Get<Student>(user.UserNo.ToString());
                    if (stu != null)
                        studentID = user.UserNo;
                    break;
                case "Admin":
                    break;
            }

            return Ok(new ObjectResponse()
            {
                Status = ResponseStatus.OK(),
                ResponseObj = AuthUtil.Authorize(user, companyID, studentID)
            });

            // return AuthUtil.Authorize(user, companyID, studentID);
        }
        #endregion

        public IHttpActionResult GetUserInfo(string id, string type)
        {
            Dictionary<string, string> dic = new Dictionary<string, string>();
            Dictionary<string, string> dicResult = new Dictionary<string, string>();

            if (type == APPRole.Student.ToString())
            {
                DisplayUtil.ListAssociation(id.ToInt(), dic, null, "Student");
                dicResult.Add("Name", dic["Name"]);
                dicResult.Add("Remark", dic["Remark"]);
                dicResult.Add("ChargeName", dic["ChargeName"]);
                dicResult.Add("Nature", dic["Nature"]);
                dicResult.Add("SchoolName", dic["SchoolName"]);
                dicResult.Add("Type", dic["Type"]);
                dicResult.Add("Scale", dic["Scale"]);
                dicResult.Add("Amount", dic["DeptAmount"]);
                dicResult.Add("Address", dic["SchoolAddress"]);

                dicResult.Add("LogoPath", dic.GetValue("LogoPath"));
                dicResult.Add("UserType", APPRole.Student.ToString());
            }
            else
            {
                var company = companyService.GetCompany(id);
                dicResult.Add("Name", company.Name);
                dicResult.Add("ChargeName", company.ChargeName);
                dicResult.Add("Nature", company.Type);
                dicResult.Add("Sign", company.Sign);
                dicResult.Add("Type", company.JobType);
                dicResult.Add("CompanyHref", company.CompanyHref);
                dicResult.Add("Scale", company.Size);
                dicResult.Add("Address", company.Address);
                dicResult.Add("LogoPath", SystemConfig.Get("UploadHttpPath") + company.LogoPath);
            }

            return Ok(new DictResponse()
            {
                Status = ResponseStatus.OK(),
                ResponseDict = dicResult
            });

        }

        [HttpGet]
        public IHttpActionResult GetSchool([FromUri]string id)
        {
            var school = AppConfig.GetSchool(id.ToInt());

            return Ok(new StringResponse()
            {
                Status = ResponseStatus.OK(),
                ResponseStr = school.SchoolName
            });
        }

        [HttpGet]
        public IHttpActionResult ListAgent()
        {
            var lst = service.ListAgent();

            return Ok(new ListResponse()
            {
                Status = ResponseStatus.OK(),
                ResponseList = lst.Select(x => (Object)x).ToList()
            });
        }

        [HttpGet]
        public IHttpActionResult GetUser()
        {
            var user = AuthUtil.GetAuthentication();
            if (user == null)
                return BadRequest();
            string userID = user.UserID.ToString();

            var userinfo = service.Get<UserInfo>(userID);

            Dictionary<string, string> dic = userinfo.ToDictionary();
            return Ok(new DictResponse()
            {
                Status = ResponseStatus.OK(),
                ResponseDict = dic
            });
        }

        [HttpGet]
        public IHttpActionResult CheckUser()
        {
            var user = AuthUtil.GetAuthentication();

            return Ok(new StringResponse()
            {
                Status = ResponseStatus.OK(),
                ResponseStr = user == null ? "N" : "Y"
            });
        }

        // PUT api/user/5
        public void Put(int id, [FromBody]string value)
        {
        }

        [HttpGet]
        public IHttpActionResult HasVerified()
        {
            var user = AuthUtil.GetAuthentication();
            if (user == null)
                return Unauthorized();

            var userinfo = service.Get<UserInfo>(user.UserID.ToString());

            if (userinfo == null)
                return Unauthorized();

            Dictionary<string, string> dic = new Dictionary<string, string>();

            if (userinfo.Status == CommonStatus.Verified)
                dic.Add("HasVerified", "Y");
            else
            {
                dic.Add("HasVerified", "N");
                dic.Add("Message", "请完成用户信息后执行此操作");

                if (userinfo.Status == CommonStatus.FiveStep)
                    dic["Message"] = "用户信息审核中，请审核通过后提交";
            }

            return Ok(new DictResponse()
            {
                Status = ResponseStatus.OK(),
                ResponseDict = dic
            });
        }


        // DELETE api/user/5
        public IHttpActionResult FindPassword()
        {
            var httpPostedForm = HttpContext.Current.Request.Form;
            string username = httpPostedForm["UserName"];
            string code = httpPostedForm["code"];
            string resp = "成功";
            var validation = service.Get<UserValidation>(username);

            if (validation == null || string.IsNullOrWhiteSpace(validation.ValidNo)
                || code != validation.ValidNo || (DateTime.Now - validation.CreatedTime).Minutes > 15)
                resp = "验证码错误";

            return Ok(new StringResponse()
            {
                Status = ResponseStatus.OK(),
                ResponseStr = resp
            });
        }

        public IHttpActionResult ResetPassword()
        {
            var httpPostedForm = HttpContext.Current.Request.Form;
            string username = httpPostedForm["UserName"];
            string code = httpPostedForm["code"];
            string password = httpPostedForm["Password"];
            string resp = "成功";
            var validation = service.Get<UserValidation>(username);

            if (validation == null || string.IsNullOrWhiteSpace(validation.ValidNo)
                || code != validation.ValidNo || (DateTime.Now - validation.CreatedTime).Minutes > 15)
                resp = "验证码错误";
            else
            {
                service.UpdatePassword(username, password);
            }

            return Ok(new StringResponse()
            {
                Status = ResponseStatus.OK(),
                ResponseStr = resp
            });
        }

        [HttpGet]
        public void Logout()
        {
            AuthUtil.Unauthorize();
        }

        [HttpPost]
        public void UploadFile(string type)
        {
            var httpPostedFile = HttpContext.Current.Request.Files;
            string strDir = SystemConfig.Get("UploadPath");
            for (int i = 0; i < httpPostedFile.Count; i++)
            {
                HttpPostedFile file = httpPostedFile[i];
                string fname = strDir + "userNameToUpper" + Path.GetExtension(file.FileName);
                file.SaveAs(fname);
            }

        }

        private string GetAgentPassword()
        {
            string strDateTimeNumber = DateTime.Now.ToString("yyyyMMddHHmmssms");
            Random ran = new Random();
            int strRandomResult = ran.Next(1, 10000);
            return strDateTimeNumber + strRandomResult;
        }
    }
}
